/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lucava.boatskeeper.client.control;

import org.lucava.lib.client.control.Control;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import org.lucava.boatskeeper.client.event.AuthEvent;
import org.lucava.boatskeeper.client.event.AuthHandler;
import org.lucava.boatskeeper.client.event.ConnectEvent;
import org.lucava.boatskeeper.client.event.DisconnectEvent;
import org.lucava.lib.client.event.InitEvent;
import org.lucava.lib.client.service.SessionService;
import org.lucava.lib.client.service.SessionServiceAsync;
import org.lucava.boatskeeper.shared.dto.UserDto;

/**
 *
 * @author glenn
 */
public class LayoutController extends Control implements AuthHandler {

    private SessionServiceAsync sessionService = GWT.create(SessionService.class);
    private Widget layout;


    @Override
    public void onInit() {
        checkSession();
    }

    @Override
    public void onInitHandlers() {
        getEventBus().addHandler(AuthEvent.TYPE, LayoutController.this);

    }

    public void setLayout(Widget layout) {
        this.layout = layout;
    }

    @Override
    public void onUserAuth(AuthEvent event) {
    }

    @Override
    public void onUserConnect(ConnectEvent event) {
    }

    @Override
    public void onUserDisconnect(DisconnectEvent event) {
    }

    private void checkSession() {

        sessionService.getUser(new AsyncCallback<UserDto>() {
            @Override
            public void onSuccess(UserDto result) {

                if (result == null) {
                    RootLayoutPanel.get().clear();
                    RootLayoutPanel.get().add(new SimplePanel());
                    getEventBus().fireEvent(new AuthEvent());
                } else {
                    RootLayoutPanel.get().clear();
                    RootLayoutPanel.get().add(layout);
                }
            }

            @Override
            public void onFailure(Throwable caught) {
                Window.alert("Impossible de récupérer l'utilisateur\n ->" + caught.getLocalizedMessage());
            }
        });
    }
}
